/**
 * 
 */
package com.youth.fund.hk.hostManager.shiro.credentials;

import java.util.concurrent.atomic.AtomicInteger;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;

/**
 * @author Sunk_Sky
 *
 * 2014年11月13日下午4:33:56
 */
public class RetryLimitHashedCredentialsMatcher extends
		HashedCredentialsMatcher
{
	private final static String PASSWORDRETRYCACHE = "passwordRetryCache";
	
	private Cache<String,AtomicInteger> passwordRetryCache;
	
	public RetryLimitHashedCredentialsMatcher(CacheManager cacheManager)
	{
		this.passwordRetryCache = cacheManager.getCache(PASSWORDRETRYCACHE);
	}

	@Override
	public boolean doCredentialsMatch(AuthenticationToken token,
			AuthenticationInfo info)
	{
		String username = (String)token.getPrincipal();
		
		AtomicInteger retryCount = passwordRetryCache.get(username);
		
		if(retryCount == null)
		{
			retryCount = new AtomicInteger(0);
			
			passwordRetryCache.put(username, retryCount);
		}
		//这个功能要不要？
		if(retryCount.incrementAndGet() > 5)
		{
			throw new ExcessiveAttemptsException("连续五次密码输入失败！用户已锁，请20分钟后重试！");
		}
		boolean matches = super.doCredentialsMatch(token, info);
		
		if(matches)
		{
			passwordRetryCache.remove(username);
		}
		
		return matches;
	}
	
	
}
